package com.caishi.lkx.exam.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caishi.lkx.common.AdminBaseApi;
import com.caishi.lkx.common.ienum.ClientType;
import com.caishi.lkx.common.ienum.DeviceType;
import com.caishi.lkx.common.role.Roles;
import com.caishi.lkx.exam.model.CategoryModel;
import com.caishi.lkx.exam.model.ExamModel;
import com.caishi.lkx.exam.service.*;
import com.caishi.lkx.exam.service.impl.MaterialInfoServiceImpl;
import com.caishi.lkx.exam.vo.ExamMaterialVo;
import com.caishi.lkx.exam.vo.IndexMaterialVo;
import com.caishi.lkx.exam.vo.MaterialInfoVo;
import com.caishi.lkx.user.service.IUserService;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.impl.BSDUAbsEntity;
import com.zzw.common.entity.impl.BaseEntity;
import com.zzw.common.entity.impl.BaseIntEntity;
import com.zzw.common.exception.BizException;
import com.zzw.common.file.OssPlugins;
import com.zzw.common.mysql.config.MybatisPlusContext;

import com.caishi.lkx.exam.ienum.type.AddFrequencyType;

import com.caishi.lkx.exam.records.RecordsCollectType;

import com.caishi.lkx.user.model.MaterialInfoModel;
import com.caishi.lkx.user.model.MaterialLikeModel;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author by liyihua
 * @date : 2022-01-06 14:29
 */
@Slf4j
@Tag(name = "资讯资料相关接口")
@RestController
@RequestMapping("/material/info")
public class MaterialInfoApi extends AdminBaseApi<MaterialInfoServiceImpl, MaterialInfoModel, String> {
    @Resource
    private MaterialInfoServiceImpl materialInfoService;
    @Resource
    private IExamService examService;
    @Resource
    private IIndustryService industryService;
    @Resource
    private IUserService userService;
    @Resource
    private IMaterialLikeService materialLikeService;
    @Resource
    private OssPlugins cdnOssPlugins;
    //    @Resource
//    private MaterialInfoEsService materialInfoEsService;
//    @Resource
//    private ElasticsearchRestTemplate esTemplate;
    // @Resource
    // private EsSearchUtil<MaterialInfoModel, String, IMaterialInfoService> esSearchUtil;
    @Resource
    private ICategoryService categoryService;
    @Resource
    private IColumnService columnService;

    @Override
    public MaterialInfoServiceImpl loadService() {
        return materialInfoService;
    }

    @DeleteMapping("/batch-delete")
    @Transactional(rollbackFor = Exception.class)
    @Operation(summary = "批量删除")
    public Boolean batchDelete(@RequestParam List<String> ids) {
        return materialInfoService.delete(ids);
    }

    @Override
    protected LambdaQueryWrapper<MaterialInfoModel> baseWrapper(MaterialInfoModel model, JSONObject otherParam) {
        return super.baseWrapper(
                        model.clearEmptyStringField("title"), otherParam)
                .like(StringUtil.isNotBlank(model.getTitle()), MaterialInfoModel::getTitle, model.getTitle())
                .orderByDesc(MaterialInfoModel::getTop)
                .orderByDesc(MaterialInfoModel::getCreatedTime);

    }

    @Override
    protected List<MaterialInfoModel> listCover(List<MaterialInfoModel> result, JSONObject otherParam) {
        Map<Long, String> cateNameMap;
        if (!result.isEmpty()) {
            List<Long> categoryIds = result.stream().map(MaterialInfoModel::getCategoryId).collect(Collectors.toList());
            cateNameMap = categoryService.selectList(categoryService.wrappers().select(CategoryModel::getName, BaseIntEntity::getId).in(categoryIds.size() > 1, BaseIntEntity::getId, categoryIds).eq(categoryIds.size() == 1, BaseIntEntity::getId, categoryIds.get(0))).stream().collect(Collectors.toMap(BaseIntEntity::getId, CategoryModel::getName, (a, b) -> b));
        } else {
            cateNameMap = Map.of();
        }
        return result.parallelStream().peek(r -> {
            r.setCategoryName(cateNameMap.get(r.getCategoryId()));
            r.setCreatedName(userService.getUserNameById(r.getCreatedBy()));
            if (!r.getAttachmentInfos().isEmpty()) {
                r.setAttachmentSize(r.getAttachmentInfos().size());
            }
        }).toList();

    }

    private Integer getAttachmentInfosSize(String attachmentInfos) {
        JSONArray jsonArray = JSON.parseArray(attachmentInfos);
        int sum = 0;
        for (int i = 0; i < jsonArray.size(); i++) {
            com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
            sum += (int) jsonObject.get("size");
        }
        return sum;
    }

    @Override
    @GetMapping("/page")
    @Roles
    public IPage<MaterialInfoModel> page(@ModelAttribute Page<MaterialInfoModel> page, @ModelAttribute MaterialInfoModel model, @NotNull JSONObject otherParam) {
        String userId = userContext.currentUserId();
        return page.setRecords(super.page(page, model, otherParam).getRecords().parallelStream().peek(v -> {
            Long aLong = materialLikeService.selectCount(Wrappers.<MaterialLikeModel>lambdaQuery().eq(MaterialLikeModel::getRelationId, v.getId())
                    .eq(BSDUAbsEntity::getCreatedBy, userId));
            v.setLike(aLong != null && aLong != 0);
        }).toList());
    }

    @GetMapping("/list")
    @Roles
    public List<MaterialInfoModel> list(@RequestParam(defaultValue = "10") Integer size, @ModelAttribute MaterialInfoModel model, @NotNull JSONObject otherParam) {
        if (size > 1000) {
            size = 1000;
        }
        return listCover(loadService().selectList(loadService().wrapperProcessing(baseWrapper(model, otherParam)), size), otherParam);
    }


    @GetMapping("index-list")
    @Operation(summary = "首页热门资讯、免费资料")
    @Parameters({
            @Parameter(name = "type", description = "类型，0.考试资讯，1.考试资料"),
            @Parameter(name = "examId", description = "考试id"),
            @Parameter(name = "num", description = "查询条数")})
    @Roles
    public IPage<MaterialInfoModel> indexList(@ModelAttribute Page<MaterialInfoModel> page, @RequestParam Boolean type, @RequestParam(required = false) String examId,@RequestParam(required = false) Long categoryId) {
        long size = page.getSize();
        DeviceType device = userContext.currentTokenData().getDevice();
        MaterialInfoModel one = null;
        String oneId = null;

        // 如果不是安卓和ios
        if (!device.equals(DeviceType.android) && !device.equals(DeviceType.ios)) {
            one = materialInfoService.selectFirst(Wrappers.<MaterialInfoModel>lambdaQuery()
                    .eq(MaterialInfoModel::getType, type)
                    .eq(StrUtil.isNotBlank(examId), MaterialInfoModel::getExamId, examId)
                    .eq(MaterialInfoModel::getRecommend, true)
                    .orderByDesc(MaterialInfoModel::getCreatedTime)
            );
            if (null != one) {
                page.setSize(size - 1);
                oneId = one.getId();
            }
        }
        // 数据库exam_id为空
        List<Long> ids = new ArrayList<>();

        if (StrUtil.isNotBlank(examId)) {
            QueryWrapper<CategoryModel> queryWrapper = new QueryWrapper<>();
            List<CategoryModel> categoryModels = categoryService.selectList(queryWrapper);
            ids = categoryModels.stream().map(CategoryModel::getId).collect(Collectors.toList());
        }

        IPage<MaterialInfoModel> resPage = materialInfoService.page(page, Wrappers.<MaterialInfoModel>lambdaQuery()
                        .eq(MaterialInfoModel::getType, type)
//                .eq(StrUtil.isNotBlank(examId), MaterialInfoModel::getExamId, examId)
                        .in(StrUtil.isNotBlank(examId), MaterialInfoModel::getCategoryId, ids)
                        .eq(categoryId!=null,MaterialInfoModel::getCategoryId, categoryId)
                        .ne(null != one, MaterialInfoModel::getId, oneId)
                        .orderByDesc(MaterialInfoModel::getRecommend)
                        .orderByDesc(MaterialInfoModel::getModifyTime)
        );
        List<MaterialInfoModel> records = resPage.getRecords();
        if (records.isEmpty()) {
            return null;
        }
        if (null != one) {
            records.add(0, one);
        }
        String userId = userContext.currentUserId();

        List<MaterialInfoModel> list = records.stream().peek(m -> {
            m.setAttachmentSize(0);
            if (StringUtil.isNotBlank(userId)) {
                MaterialLikeModel likeModel = materialLikeService.selectOne(Wrappers.<MaterialLikeModel>lambdaQuery().eq(MaterialLikeModel::getRelationId, m.getId())
                        .eq(BSDUAbsEntity::getCreatedBy, userId));
                m.setLike(likeModel != null);
            }
            if (!m.getAttachmentInfos().isEmpty()) {
                m.setAttachmentSize(m.getAttachmentInfos().size());
            }
        }).toList();
        resPage.setRecords(list);
        return resPage;
    }

    @PutMapping("add-frequency")
    @Operation(summary = "增加下载次数、查看次数")
    @Parameters({
            @Parameter(name = "type", description = "类型"),
            @Parameter(name = "id", description = "资讯id")})
    @Roles
    public void addFrequency(@RequestParam AddFrequencyType type, @RequestParam String id) {
        MybatisPlusContext.setContext(new MybatisPlusContext.Context().setNoUpdateModifyTime(true));
        switch (type) {
            case download_time:
                materialInfoService.update(null, Wrappers.<MaterialInfoModel>lambdaUpdate().eq(BaseEntity::getId, id).setSql("download_time=download_time+1"));
                break;
            case watch_time:
                materialInfoService.update(null, Wrappers.<MaterialInfoModel>lambdaUpdate().eq(BaseEntity::getId, id).setSql("watch_time=watch_time+1"));
                break;
        }
    }

    @GetMapping("get-like-status")
    @Operation(summary = "获取点赞收藏状态")
    @Parameter(name = "id", description = "关联id")
    public Boolean getLikeStatus(@RequestParam String id) {
        MaterialLikeModel materialLikeModel = materialLikeService.selectOne(Wrappers.<MaterialLikeModel>lambdaQuery().eq(MaterialLikeModel::getRelationId, id)
                .eq(BSDUAbsEntity::getCreatedBy, userContext.currentUserId()));
        return null != materialLikeModel && materialLikeModel.getPassive() == 1;
    }


    @PutMapping("update-like")
    @Operation(summary = "点赞收藏")
    @Parameters({
            @Parameter(name = "id", description = "关联id"),
            @Parameter(name = "type", description = "类型：0.资讯点赞 1.试卷收藏"),
            @Parameter(name = "recordsCollectType", description = "试卷类型")
    })
    public Boolean updateLike(@RequestParam String id, @RequestParam Integer type, @RequestParam(required = false) Long categoryId, @RequestParam(required = false) RecordsCollectType recordsType) {
        MybatisPlusContext.setContext(new MybatisPlusContext.Context().setNoUpdateModifyTime(true));
        String userId = userContext.currentUserId();
        if (StringUtil.isNotBlank(userId)) {
            MaterialLikeModel likeModel = materialLikeService.selectOne(Wrappers.<MaterialLikeModel>lambdaQuery()
                    .eq(MaterialLikeModel::getRelationId, id)
                    .eq(MaterialLikeModel::getType, type)
                    .eq(BSDUAbsEntity::getCreatedBy, userId));
            if (type == 1 && null != likeModel && likeModel.getPassive() != 1) {
                likeModel.setPassive(1);
                materialLikeService.update(likeModel);
                return true;
            }
            //有就删除、无则删除
            if (likeModel == null) {
                likeModel = new MaterialLikeModel();
                likeModel.setRelationId(id);
                likeModel.setType(type);
                likeModel.setCreatedBy(userId);
                likeModel.setCategoryId(categoryId);
                likeModel.setRecordsType(recordsType);
                likeModel.setPassive(1);
                if (type == 0) {
                    materialInfoService.update(null, Wrappers.<MaterialInfoModel>lambdaUpdate().eq(BaseEntity::getId, id).setSql("like_time=like_time+1"));
                }
                return materialLikeService.insert(likeModel) != null;
            } else {
                if (type == 0) {
                    materialInfoService.update(null, Wrappers.<MaterialInfoModel>lambdaUpdate().eq(BaseEntity::getId, id).gt(MaterialInfoModel::getLikeTime, 0).setSql("like_time=like_time-1"));
                }
                return materialLikeService.delete(likeModel.getId());
            }
        }
        return false;

    }


    @GetMapping("detail-page")
    @Operation(summary = "详情页")
    @Parameter(name = "id", description = "资讯id")
    @Roles
    public MaterialInfoVo detailPage(@RequestParam String id) {
        MaterialInfoModel infoModel = materialInfoService.getById(id);
        MaterialInfoVo vo = new MaterialInfoVo();
        BeanUtil.copyProperties(infoModel, vo);
        vo.setLike(false);
        MaterialInfoModel previous = null;
        MaterialInfoModel next = null;
        String userId = userContext.currentUserId();
        //上下一条
        if (infoModel != null) {
            //上一条
            previous = materialInfoService.selectFirst(Wrappers.<MaterialInfoModel>lambdaQuery()
                    // .orderByDesc(MaterialInfoModel::getTop)
                    .orderByAsc(MaterialInfoModel::getCreatedTime)
                    .ge(MaterialInfoModel::getCreatedTime, infoModel.getCreatedTime())
                    .eq(MaterialInfoModel::getExamId, infoModel.getExamId())
                    .ne(MaterialInfoModel::getId, id)
                    .eq(MaterialInfoModel::getType, infoModel.getType())
            );
            //下一条
            next = materialInfoService.selectFirst(Wrappers.<MaterialInfoModel>lambdaQuery()
                    //.orderByDesc(MaterialInfoModel::getTop)
                    .orderByDesc(MaterialInfoModel::getCreatedTime)
                    .le(MaterialInfoModel::getCreatedTime, infoModel.getCreatedTime())
                    .ne(MaterialInfoModel::getId, id)
                    .eq(MaterialInfoModel::getExamId, infoModel.getExamId())
                    .eq(MaterialInfoModel::getType, infoModel.getType())
            );
        }
        if (StringUtil.isNotBlank(userId)) {
            MaterialLikeModel materialLikeModel = materialLikeService.selectOne(Wrappers.<MaterialLikeModel>lambdaQuery().eq(MaterialLikeModel::getRelationId, id)
                    .eq(BSDUAbsEntity::getCreatedBy, userId));
            if (materialLikeModel != null) {
                vo.setLike(true);
            }
        }
        vo.setPreviousName(previous != null ? previous.getTitle() : "暂无上一篇");
        vo.setPreviousId(previous != null ? previous.getId() : null);
        vo.setNextName(next != null ? next.getTitle() : "暂无下一篇");
        vo.setNextId(next != null ? next.getId() : null);
        vo.setCreatedName(userService.queryName(infoModel.getCreatedBy()));
        return vo;
    }

    @GetMapping("about-infos")
    @Operation(summary = "相关阅读")
    @Roles
    public List<MaterialInfoModel> aboutInfos(@RequestParam String id) {
        MaterialInfoModel materialInfoModel = materialInfoService.getById(id);
        String userId = userContext.currentUserId();
        return materialInfoService.selectList(Wrappers.<MaterialInfoModel>lambdaQuery()
                        .eq(MaterialInfoModel::getType, materialInfoModel.getType())
                        .eq(MaterialInfoModel::getExamId, materialInfoModel.getExamId())
                        .orderByDesc(MaterialInfoModel::getWatchTime), 4)
                .parallelStream().peek(m -> {
                    m.setLike(false);
                    if (StringUtil.isNotBlank(userId)) {
                        MaterialLikeModel likeModel = materialLikeService.selectOne(Wrappers.<MaterialLikeModel>lambdaQuery().eq(MaterialLikeModel::getRelationId, id)
                                .eq(BSDUAbsEntity::getCreatedBy, userId));
                        m.setLike(likeModel != null);
                    }
                }).toList();
    }

    @GetMapping("my-like")
    @Operation(summary = "我的点赞")
    public IPage<MaterialInfoModel> myLike(@ModelAttribute Page<MaterialInfoModel> page) {
        IPage<MaterialInfoModel> resPage = new Page<>();
        String userId = userContext.currentUserId();
        //"and id in (select relation_id from sys_material_like where type=0 and deleted = 0 and created_by= '" + userId + "' order by created_time DESC)")
        if (StringUtil.isNotBlank(userId)) {
            resPage = materialInfoService.myLikePage(page, userId);
            resPage.getRecords().parallelStream().forEach(m -> {
                m.setLike(true);
                if (!m.getAttachmentInfos().isEmpty()) {
                    m.setAttachmentSize(m.getAttachmentInfos().size());
                }
            });
        }
        return resPage;
    }


    @GetMapping("hot-infos")
    @Operation(summary = "热门指定资讯")
    @Roles
    public IndexMaterialVo hotInfos() {
        //获取飘红推荐
        List<MaterialInfoModel> materialInfoModels = materialInfoService.selectList(Wrappers.<MaterialInfoModel>lambdaQuery().eq(MaterialInfoModel::getHot, true).orderByDesc(MaterialInfoModel::getModifyTime), 8);
        IndexMaterialVo indexMaterialVo = new IndexMaterialVo();
        indexMaterialVo.setHotInfos(materialInfoModels);
//        //热门资讯
        List<MaterialInfoModel> models = materialInfoService.selectList(Wrappers.<MaterialInfoModel>lambdaQuery().eq(MaterialInfoModel::getTop, true).eq(MaterialInfoModel::getType, false).orderByDesc(MaterialInfoModel::getModifyTime).select(MaterialInfoModel::getExamId));
        List<String> list = models.stream().map(MaterialInfoModel::getExamId).toList();
        Set<String> set = new LinkedHashSet();
        list.forEach(l -> {
            if (set.size() < 8) {
                set.add(l);
            }
        });
        List<ExamMaterialVo> examMaterialVolist = new ArrayList<>();
        set.forEach(e -> {
            ExamModel examModel = examService.getById(e);
            ExamMaterialVo examMaterialVo = new ExamMaterialVo();
            examMaterialVo.setAlias(examModel.getServerName());
            examMaterialVo.setExamName(examModel.getName());
            examMaterialVo.setExamId(e);
            List<MaterialInfoModel> infoModels = materialInfoService.selectList(Wrappers.<MaterialInfoModel>lambdaQuery()
                    .eq(MaterialInfoModel::getExamId, e)
                    .eq(MaterialInfoModel::getTop, true)
                    .eq(MaterialInfoModel::getType, false)
                    .orderByDesc(MaterialInfoModel::getModifyTime), 4
            );
            examMaterialVo.setInfos(infoModels);
            examMaterialVolist.add(examMaterialVo);
        });
        indexMaterialVo.setTopInfos(examMaterialVolist);
        return indexMaterialVo;


    }


    @GetMapping("get-zip-download")
    @Operation(summary = "打包下载资料")
    @Parameter(name = "materialId", description = "资料id", required = true)
    public void getZipDownload(String materialId, HttpServletResponse response) {
        MaterialInfoModel materialInfoModel = materialInfoService.getById(materialId);
       /* if (null != materialInfoModel && StringUtil.isNotBlank(materialInfoModel.getAttachmentInfos())) {
            JSONArray array = JSON.parseArray(materialInfoModel.getAttachmentInfos());
            List<Map<String, Object>> fileList = new ArrayList<>();
            array.parallelStream().forEach(a -> {
                Map<String, Object> byteMap = new HashMap<>();
                com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) a;
                String url = jsonObject.getString("url");
                if (StringUtil.isBlank(url)) {
                    return;
                }
                int i = url.indexOf("@");
                String fileName = url.substring(i + 1);
                byteMap.put("fileName", fileName);
                try {
                    byte[] bytes = cdnOssPlugins.getObject(url);
                    byteMap.put("byte", bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fileList.add(byteMap);
            });
            //更新下载次数
            try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream()); OutputStream os = null;) {
                response.setContentType("application/zip");
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("附件.zip", StandardCharsets.UTF_8));
                // 创建 ZipEntry 对象
                for (Map<String, Object> map : fileList) {
                    ZipEntry zipEntry = new ZipEntry((String) map.get("fileName"));
                    zipOutputStream.putNextEntry(zipEntry);
                    zipOutputStream.write((byte[]) map.get("byte"));
                }

            } catch (IOException e) {
                log.error("压缩包导出失败=》" + e);
            }
        }*/
    }

    @GetMapping("get-info-index")
    @Operation(summary = "首页搜索资讯")
    @Parameter(name = "keyword", description = "搜索词")
    @Roles
    public Page<MaterialInfoModel> getInfoIndex(@ModelAttribute Page<MaterialInfoModel> page, @ModelAttribute MaterialInfoModel model, @RequestParam String keyword, @RequestParam(defaultValue = "false") Boolean isSort) throws IOException {
        /*if (Sensitive.isSensitive(keyword)) {
            return page;
        }
        Map<String, Object> title = MapUtil.<String, Object>builder().put("value", keyword).put("boost", 2).build();
        Map<String, Object> content = MapUtil.<String, Object>builder().put("value", keyword).put("boost", 1).build();
        Map<String, Map<String, Object>> shouldMap = new HashMap<>();
        shouldMap.put("title", title);
        shouldMap.put("content", content);
        Map<String, Object> mustMap = new HashMap<>();
        Map<String, Object> filterMap = new HashMap<>();
        if (StringUtil.isNotBlank(model.getExamId())) {
            filterMap.put("examId", model.getExamId());
        }
        if (StringUtil.isNotBlank(model.getIndustryId())) {
            filterMap.put("industryId", model.getIndustryId());
        }
        Map<String, SortOrder> sort = new HashMap<>();
        if (isSort) {
            sort.put("createTime", SortOrder.DESC);
        }
        Map<String, Object> resMap = esSearchUtil.esByConditions(page, shouldMap, mustMap, filterMap, null, sort, "vip-vers7_material_info", materialInfoService, "title", "content");
        Map<String, Map<String, String>> replaceMap = (Map<String, Map<String, String>>) resMap.get("replaceMap");
        Page<MaterialInfoModel> resPage = (Page<MaterialInfoModel>) resMap.get("page");
        resPage.getRecords().stream().peek(r -> {
            r.setAttachmentSize(this.getAttachmentInfosSize(r.getAttachmentInfos()));
            MaterialLikeModel likeModel = materialLikeService.selectOne(Wrappers.<MaterialLikeModel>lambdaQuery().eq(MaterialLikeModel::getCreatedBy, userContext.currentUserId())
                    .eq(MaterialLikeModel::getRelationId, r.getId()).eq(MaterialLikeModel::getType, false).select(MaterialLikeModel::getId));
            r.setLike(null != likeModel);
            if (replaceMap.get(r.getId()) != null) {
                if (StringUtil.isNotBlank(replaceMap.get(r.getId()).get("title"))) {
                    r.setTitle(replaceMap.get(r.getId()).get("title"));
                }
                if (StringUtil.isNotBlank(replaceMap.get(r.getId()).get("content"))) {
                    r.setContent(replaceMap.get(r.getId()).get("content"));
                }
            }
        }).toList();
        return resPage;*/
        return null;

    }

//    @GetMapping("/createEsIndex")
//    public void createEsIndex() {
//        String[] arr = {"title", "content"};
//        esSearchUtil.createIndex("material_info", Arrays.asList(arr));
//    }

    @DeleteMapping("/delete")
    public Boolean delete(@RequestParam String id) {
       /* Map<String, Object> map = MapUtil.<String, Object>builder()
                .put("id", id).build();
        try {
             esSearchUtil.deleteDoc("material_info",map );
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        //materialInfoEsService.delete(id);
        return loadService().delete(id);
    }


//    @PostMapping("/syncES")
//    @Operation(description = "同步资讯到es")
//    public void syncES() {
//        List<MaterialInfoModel> materialInfoModels = loadService().selectList(Wrappers.<MaterialInfoModel>lambdaQuery());
//        int count = 1;
//        List<MaterialInfoEs> models = new ArrayList<>();
//        for (MaterialInfoModel model : materialInfoModels) {
//            MaterialInfoEs materialInfoEs = new MaterialInfoEs();
//            BeanUtil.copyProperties(model, materialInfoEs);
//            materialInfoEs.setCreateTime(model.getModifyTime().toEpochSecond(ZoneOffset.ofHours(8)));
//            models.add(materialInfoEs);
//            if (count % 500 == 0) {
//                materialInfoEsService.batchUpdate(models);
//                models.clear();
//            }
//            count++;
//        }
//        if (!models.isEmpty()) {
//            materialInfoEsService.batchUpdate(models);
//        }
//
//    }

    @GetMapping("/material-by-columnId")
    @Operation(summary = "根据栏目拉取资料列表")
    @Parameters({
            @Parameter(name = "columnId", description = "栏目id", required = true),
            @Parameter(name = "page", description = "分页模型"),
    })
    @Roles
    public IPage<MaterialInfoModel> getPaperForColumn(@ModelAttribute Page<MaterialInfoModel> page,
                                                      @RequestParam(required = true) String columnId,
                                                      @RequestParam String industryCode,
                                                      @RequestParam String examId,
                                                      @RequestParam Long categoryId
    ) throws BizException {

        Map<String, Object> param = MapUtil.<String, Object>builder()
                .put("columnId", columnId).build();
        var userId = userContext.currentUserId();

        MaterialInfoModel m = new MaterialInfoModel();

        IPage<MaterialInfoModel> resultPage = this.loadService().materialInfoByColumnIdPage(page, param);
        if (StrUtil.isNotBlank(userId)) {
            boolean freeFlag = columnService.currentHaveAuth(null, null, userId, categoryId, columnId, ClientType.zyksApp);
            resultPage.getRecords().forEach(materialInfoModel -> {
                if (!materialInfoModel.getFreeFlag())
                    materialInfoModel.setFreeFlag(freeFlag);

            });
        }
        return resultPage;
    }

    @PostMapping(value = "batch-add-infomaterial")
    @Roles
    public void batchAddInfoMaterial(@RequestBody MaterialInfoModel materialInfoModel) {
        AtomicInteger index = new AtomicInteger(1);
        List<MaterialInfoModel> list = new ArrayList<>();
        materialInfoModel.getAttachmentInfos().forEach(item ->
        {
            int currentIndex = index.getAndIncrement();
            list.add(MaterialInfoModel.builder().categoryId(materialInfoModel.getCategoryId()).title(item.get("name").toString().split("\\.")[0]).sort(currentIndex).attachmentInfos(List.of(item)).materialType(materialInfoModel.getMaterialType()).type(true).build());
        });
        loadService().insertBatch(list);
    }
}
